/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.shuffling;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 * @author Czarek
 */
public class ShufflingIdGenerator implements IShufflingIdGenerator {

    //private static final int MAX_ID=16;
    private static final int oddIncrement = 2;
    
    private static final int evenIncrement = 2;
    private int odd = 1;
    private int even = 0;
    private boolean flip=false;
    //private AtomicBoolean last = new AtomicBoolean();

    public int getNextId(final int prev, final boolean condition) {
        final int result;
        if (prev % 2 == 0^condition) {
            result =  (odd += oddIncrement) ;
        } else {
            result = (even += evenIncrement) ;
        }
        
        return result;
    }

    @Override
    public void assureIds(IShufflable shuffable1, IShufflable shuffable2, boolean condition) {
        Integer sid1 = shuffable1.getShuffleId();
        Integer sid2 = shuffable2.getShuffleId();
        if (sid1 != null && sid2 != null) {
            return;
        }

        final Integer prev = (sid1 != null ? sid1 : sid2);
        int iPrev =(prev != null) ? prev : ((true)?0:1);
        if (sid1 == null&&shuffable1!=shuffable2) {
            final int genId = getNextId(iPrev, condition);
            iPrev = genId;
            shuffable1.setShuffleId(genId);
        }
        if (sid2 == null) {
            shuffable2.setShuffleId(getNextId(iPrev, condition));
        }
    }
    
    @Override
    public String toString() {
        return "ShufflingIdGenerator{" + '}';
    }
}
